package com.santu.edu.supporter.interceptor;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author luoyaoqi
 * @createTime 2024/2/23
 * @description
 */
public class ReturnValueHandler implements HandlerMethodReturnValueHandler {

    private final HandlerMethodReturnValueHandler returnValueHandler;

    public ReturnValueHandler(HandlerMethodReturnValueHandler returnValueHandler) {
        this.returnValueHandler = returnValueHandler;
    }

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        return returnValueHandler.supportsReturnType(methodParameter);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest) throws Exception {
        Method method = methodParameter.getMethod();
        if (method != null) {
            RespJson respJson = method.getAnnotation(RespJson.class);
            if (respJson == null || respJson.required()) {
                int code = respJson == null ? 200 : respJson.code();
                Map<String, Object> resultMap = new HashMap<>(6);
                resultMap.put("code", code);
                resultMap.put("data", returnValue);
                resultMap.put("msg", "成功");
                returnValue = resultMap;
            }
        }
        returnValueHandler.handleReturnValue(returnValue, methodParameter, modelAndViewContainer, nativeWebRequest);

    }
}
